package com.ltg.file.minio.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.ltg.file.config.FileDriver;
import com.ltg.file.entity.FileInfo;
import com.ltg.file.exception.FileException;
import com.ltg.file.minio.properties.MinioProperties;
import com.ltg.file.minio.utils.MinioUtils;
import com.ltg.file.sevice.FileService;
import io.minio.*;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;


/**
 * <p> ClassName: MinioFileService </p>
 * <p> Package: com.ltg.file.minio.service.impl </p>
 * <p> Description: </p>
 * <p></p>
 *
 * @Author: LTG
 * @Create: 2023/5/21 - 11:16
 * @Version: v1.0
 */
@Service
public class MinioFileService implements FileService {

    @Resource
    private MinioUtils minioUtils;


    @Resource
    private MinioProperties minioProperties;

    @Resource
    private IdentifierGenerator idGenerator;


    @Override
    public FileInfo upload(MultipartFile file) {
        String extensionName = FileNameUtil.getSuffix(file.getOriginalFilename());
        String id = idGenerator.nextUUID(null);
        String filename = id + "." + extensionName;
        String contentType = file.getContentType();
        String originName = file.getOriginalFilename();
        String objectUrl;
        try {
            InputStream fileInputStream = file.getInputStream();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())   //储存桶名称
                    .object(filename)                      //文件路径加文件名
                    .stream(fileInputStream, file.getSize(), -1)
                    .contentType(contentType)
                    .build();
            InputStream object = minioUtils.getObject();
            objectUrl = minioUtils.getUploadObjectUrl(minioProperties.getBucketName(), minioProperties.getEndpoint(), 0);
        } catch (Exception e) {
            throw new FileException(e.getMessage());
        }
        return FileInfo.builder()
                .id(id)
                .drive(FileDriver.MINIO_DRIVER)
                .originName(originName)
                .extensionName(extensionName)
                .contentType(contentType)
                .fileSize(file.getSize())
                .path(minioProperties.getBucketName())
                .downloadUrl("")
                .url(objectUrl)
                .fileName(filename)
                .id(id)
                .build();
    }
}
